package com.bxait.toymail.auth.server.controller;

import com.alibaba.fastjson.TypeReference;
import com.bxait.com.constant.AuthServerConstant;
import com.bxait.com.utils.R;
import com.bxait.toymail.auth.server.feign.MemberFeignService;
import com.bxait.com.vo.member.UserLoginVo;
import com.bxait.com.vo.member.UserRegisterVo;
import com.bxait.com.vo.member.MemberRespVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.protocol.HttpRequestHandler;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/*
@description: 处理用户登录的请求
@ClassName LoginController
@author Chen
@create 2023-04-21 9:03
@Version 1.0
*/
@Slf4j
@Controller
public class LoginController {


    @Resource
    MemberFeignService memberFeignService;

    @Resource
    StringRedisTemplate stringRedisTemplate;


    /*
     * @param session
     * @==============History===============<br/>
     * @Description //   处理去登录页面的请求
     * @Date 2023/4/21 2023/4/21
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return [javax.servlet.http.HttpSession]
     */
    @GetMapping("/login.html")
    public String loginPage(HttpServletRequest request){
        Object attribute = request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
        if(attribute == null){
            //没登录
            return "login";
        }else {
            return "redirect:http://toymail.com";
        }
    }


//    @ResponseBody
//    @GetMapping({"/get"})
//    public String get(HttpServletRequest request){
//        final Object key = request.getSession().getAttribute("key");
//        log.error("attribute-------->>>"+key);
//        return key.toString();
//    }
//
//    @ResponseBody
//    @GetMapping({"/set"})
//    public String set(HttpServletRequest request){
//        request.getSession().setAttribute(AuthServerConstant.LOGIN_USER,"666");
//        String key = (String) request.getSession().getAttribute("key");
//        return key;
//    }


    /*
     * @param vo
     * @param redirectAttributes
     * @param session
     * @==============History===============<br/>
     * @Description //   处理登录的请求
     * @Date 2023/4/21 2023/4/21
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return []
     */
    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes,
                        HttpServletRequest request){
        //远程登录
        R login = memberFeignService.login(vo);
        if(login.getCode()==0){
            MemberRespVo data = login.getData("data", new TypeReference<MemberRespVo>() {});
            ////成功放到session中
            request.getSession().setAttribute(AuthServerConstant.LOGIN_USER,data);
            return "redirect:http://toymail.com";
        }else {
            Map<String,String > errors = new HashMap<>();
            errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.toymail.com/login.html";
        }
    }

    /*
     * @param vo
     * @param redirectAttributes
     * @param request
     * @==============History===============<br/>
     * @Description //   处理微信回调之后的登录请求
     * @Date 2023/5/7 2023/5/7
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return java.lang.String
     */
    @GetMapping("/weixinLonin")
    public String weiXinLogin(@RequestParam("id") Long id, RedirectAttributes redirectAttributes,
                              HttpServletRequest request){
        // 远程换取用户信息
        R login = memberFeignService.memberInfo(id);
        if(login.getCode()==0){
            MemberRespVo data = login.getData("member", new TypeReference<MemberRespVo>() {});
            ////成功放到session中
            request.getSession().setAttribute(AuthServerConstant.LOGIN_USER,data);
            return "redirect:http://toymail.com";
        }else {
            Map<String,String > errors = new HashMap<>();
            errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.toymail.com/login.html";
        }
    }

    /*
     * @param registerVo          用户注册的数据
     * @param result              校验vo的结果
     * @param redirectAttributes  重定向需要共享数据要用这个 RedirectAttributes
     * @param session
     * @==============History===============<br/>
     * @Description //  用户注册的方法
     * @Date 2023/4/21 2023/4/21
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return java.lang.String
     */
    @PostMapping("/register")
    public String register(@Valid UserRegisterVo registerVo, BindingResult result,
                         RedirectAttributes redirectAttributes,
                         HttpSession session){

        // 1.检验注册用户出现异常返回异常数据
        if(result.hasErrors()){
            // 收集错误信息,将错误信息封装成一个map,map的key是错误字段,map的value值是错误信息
            Map<String, String> errors
                    = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors",errors);
            // 检验失败,返回注册页面
            return "redirect:http://auth.toymail.com/reg.html";
        }

        // 2.校验成功,验证手机验证码
        String code = registerVo.getCode();
        // 获取当时这个用户发送的验证码,如果在redis中已经不存在了,就让他重新获取验证码进行注册
        String redisCode =
                stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + registerVo.getPhone());
        if(!StringUtils.isEmpty(redisCode)){
            // 调用远程服务,进行用户注册
            R r = memberFeignService.register(registerVo);
            if(r.getCode() == 0){
                // 注册成功,返回登录页进行登录
                return "redirect:http://auth.toymail.com/login.html";
            }else {
                // 注册失败,返回失败消息,到注册页
                Map<String, String> errors = new HashMap<>();
                errors.put("msg",r.getData("msg",new TypeReference<String>(){}));
                redirectAttributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.toymail.com/reg.html";
            }
        }else {
            Map<String, String> errors =  new HashMap<>();
            errors.put("code","验证码错误");
            redirectAttributes.addFlashAttribute("errors",errors);
            //校验出错，转发到注册页
            return "redirect:http://auth.toymail.com/reg.html";
        }
    }


}
